package com.health.config;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-06-22 08:39
 */
@Component
public class AliyunOssClient {

    String accessKeyId = "LTAI5t5y5fWxu88puMb7vkqP";
    String secretAccessKey = "IGPiQSqCgs5zKhuwTdITvnErNX73vq";
    String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";
    String host = "oss-cn-guangzhou.aliyuncs.com";
    // 填写Bucket名称，例如examplebucket。
    String bucketName = "health-ghy";
    String region = "cn-guangzhou";
    OSS ossClient;

    public AliyunOssClient(){
        DefaultCredentialProvider credentialsProvider =
                CredentialsProviderFactory.newDefaultCredentialProvider(accessKeyId, secretAccessKey);
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V1);
        ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
    }

    /**
     * 文件上传
     * @param in 文件流
     * @param filename 文件名
     * @return 文件访问路径
     */
    public String uploadFile(InputStream in, String filename) throws RuntimeException {
        try {
            String suffix = filename.substring(filename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString().replaceAll("-", "").concat(suffix);
            String objectName = "setmeal_images/" + newFilename;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, in);
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println(result);
            //https://guohuanyang.oss-cn-hangzhou.aliyuncs.com/setmeal_imgs/13.jpg
            return "https://" + bucketName + "." + host + "/" + objectName;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("文件上传错误:" + e.getMessage());
        }
    }
}
